<template>
	<!-- 定期排查填写流程页面 -->
	<view class="workApply-container" :style="{ height: `${windowHeight}px` }">
		<!-- 基础表单校验 -->
		<uni-forms ref="valiForm" :rules="rules" :modelValue="valiFormData" border>


			<uni-forms-item label="隐患名称：" required name="hiddenDangerName">
				<uni-easyinput v-model="valiFormData.hiddenDangerName" disabled placeholder="请输入"
					:inputBorder="false" />
			</uni-forms-item>
			<!-- 上面选择检查计划回写上来的 -->
			<uni-forms-item label="隐患等级：" required name="hiddenDangerLevel">
				<uni-data-checkbox v-model="valiFormData.hiddenDangerLevel" disabled
					:localdata="hiddenLevelOption"></uni-data-checkbox>
			</uni-forms-item>

			<!-- 上面选择检查计划回写上来的 -->
			<uni-forms-item label="隐患描述：" required name="hiddenDangerInfo">
				<uni-easyinput type="textarea" v-model="valiFormData.hiddenDangerInfo" disabled placeholder="请输入"
					:inputBorder="false" />

			</uni-forms-item>

			<uni-forms-item label="审批操作：" required name="approvalStatus">
				<uni-data-checkbox v-model="valiFormData.approvalStatus"
					:localdata="approvalStatusOption"></uni-data-checkbox>
			</uni-forms-item>
			<tempplate v-if="valiFormData.approvalStatus == 1">
				<view class="title"> 负责人签字 </view>
				<view class="charge-people">

					<view class="sign"
						v-if="valiFormData.approvalStatus == 1 && (valiFormData.url == '' || valiFormData.url == null)"
						@click="handleSign()"> 请在这个区域进行签字
					</view>
					<view v-if="valiFormData.url != '' && valiFormData.url != null ">
						<image :src="valiFormData.url"></image>
					</view>
					<!-- <view class="time">月 日 时 分</view> -->
				</view>
			</tempplate>
			<tempplate v-if="valiFormData.approvalStatus == 3">
				<uni-forms-item label="转办人：" required name="subContractorId">

					<!-- <custom-tree-select :listData="allUsers" dataLabel="nickName" dataValue="userId"  disabled dataLabel="label" dataValue="id" :search="true"
					:mutiple="false" v-model="valiFormData.subContractorId" />

				</custom-tree-select> -->
					<uni-data-select v-model="valiFormData.subContractorId" :localdata="allUsers"
						:arrayConfig="configParams"></uni-data-select>

				</uni-forms-item>
			</tempplate>
			<uni-forms-item label="审批/转办意见：" required name="approvalRemark">
				<uni-easyinput type="textarea" v-model="valiFormData.approvalRemark" placeholder="请输入"
					:inputBorder="false" />
			</uni-forms-item>

		</uni-forms>

		<button type="primary" @click="submit('valiForm')" class="submit-btn">
			确认
		</button>
		<!-- 签字弹窗 -->
		<uni-popup ref="popup" type="center" width="100%" background-color="#fff" height="600px">
			<uni-nav-bar back-text="返回" title="签字"></uni-nav-bar>

			<view style="width: 750rpx ;height: 500rpx;">
				<jp-signature ref="signatureRef"></jp-signature>
			</view>
			<view>
				<button @click="clear">清空</button>
				<button @click="undo">撤消</button>
				<button @click="save">保存</button>
			</view>
			</u-form>
		</uni-popup>

	</view>
</template>

<script>
	import widowHeightMixins from "@/mixins/widowHeightMixins.js";
	import ManualSelect from "../otherViews/modal/manualSelect.vue"
	import {
		getNowTime
	} from "@/utils/nowTime.js"
	import {
		submitAllShoot,
		addAllShoot,
	} from "@/api/hiddenTrouble/allShoot.js";
	import {
		listCheckPlan,
		getCheckPlan

	} from "@/api/hiddenTrouble/checkPlan.js"
	import {
		getInfo,
		listUser
	} from "@/api/system/user.js"
	import {
		deptTreeSelect
	} from "@/api/system/user";
	import {
		mapGetters
	} from "vuex"
	export default {
		mixins: [widowHeightMixins],
		components: {
			ManualSelect
		},
		onLoad(e) {
			// console.log(e, "e");
			const eventChannel = this.getOpenerEventChannel()
			eventChannel.on('acceptDataFromOpenedPage', (data) => {
				this.queryForm.pageStatus = data.pageStatus
				console.log("接受", data)
				this.valiFormData = data.detailData


				if (data.operateStatus == 1) {
					this.handleopen(data.detailData)
				}

			});
			// 动态设置标题
			uni.setNavigationBarTitle({
				title: `全员排查--审批`,
			});
		},
		data() {
			return {
				//人员的格式化
				configParams: {
					valueKey: "userId",
					labelKey: "nickName"
				},
				//隐患登记
				hiddenForm: {},
				//详情
				detailObj: {},
				hiddenLevelOption: [{
						text: '一般隐患',
						value: 1
					},
					{
						text: '重大隐患',
						value: 2
					},

				],
				approvalStatusOption: [{
						text: '通过',
						value: 1
					},
					{
						text: '拒绝',
						value: 2
					},
					{
						text: '转办',
						value: 3
					},
				],

				//隐患登记表
				hiddentroubleInspectionRegisters: [],
				//当前选中
				current: 0,
				//标签
				items: ['检查记录表', '隐患登记表'],
				//选中ID
				checkId: null,
				//操作状态
				operateStatus: null,
				//上传参数对象
				queryForm: {},

				//被检查单位的数据
				treeData: [],
				// 校验表单数据
				valiFormData: {
					url: '',
					fileInfoList: []
				},
				taskLevelOption: [],

				//检查表内容
				tableData: [{
						id: "999",
						inspectionScopeName: "其他",
						inspectionCategoryName: "其他",
					},

				],

				// 数据总量
				total: 0,
				loading: false,
				//检查执行人
				executorList: [],


				// 校验规则
				rules: {
					dept: {
						rules: [{
							required: true,
							errorMessage: "姓名不能为空",
						}, ],
					},
					name: {
						rules: [{
							required: true,
							errorMessage: "姓名不能为空",
						}, ],
					},
					age: {
						rules: [{
								required: true,
								errorMessage: "年龄不能为空",
							},
							{
								format: "number",
								errorMessage: "年龄只能输入数字",
							},
						],
					},
				},
			};
		},
		methods: {
			//登记按钮（打开抽屉）
			handleResigration(row) {
				// this.$refs['showLeft'].open()
				uni.navigateTo({
					url: `/pages/trouble/process/registration`,
					success: (res) => {
						res.eventChannel.emit('registrationAcct', {
							detail: this.detailObj.summaryTwo,
							checkId: this.checkId,
							tableId: row.id
						})
					}
				})
			},
			//保存
			save() {
				let config = require('@/config.js')
				// 是否为空画板 无签名

				this.$refs.signatureRef.canvasToTempFilePath({
					success: (res) => {
						// 生成图片的临时路径
						// H5 生成的是base64
						if (res.isEmpty == false) {
							// this.url = res.tempFilePath
							let blob = this.dataURLtoBlob(res.tempFilePath);
							// 拿到文件名
							let fileName = "电子签名.jpg";
							// 2，在转为 file类型
							let file = this.blobToFile(blob, fileName);
							const formData = new FormData();
							formData.append("file", file);

							uni.uploadFile({
								url: `${config.baseUrl}/common/upload`,
								header: {
									'Authorization': 'Bearer ' + uni.getStorageSync(
										'App-Token') //请求头信息
								},
								filePath: res.tempFilePath,
								name: 'file',
								success: (res) => {
									let response = JSON.parse(res.data)
									response.type = "30" //全员排查审批
									response.fileId = response.id
									delete response.code
									delete response.msg
									delete response.systemTime
									delete response.originalFilename
									this.valiFormData.fileInfoList = [response]
									
									this.$set(this.valiFormData, "url", response.url)

									this.$refs.popup.close()

								}
							})
						}
					}
				})
			},

			//1,先将base64转换为blob
			dataURLtoBlob(baseurl) {
				var arr = baseurl.split(","),
					mime = arr[0].match(/:(.*?);/)[1],
					bstr = atob(arr[1]),
					n = bstr.length,
					u8arr = new Uint8Array(n);
				while (n--) {
					u8arr[n] = bstr.charCodeAt(n);
				}
				return new Blob([u8arr], {
					type: mime
				});
			},
			//2,再将blob转换为file
			blobToFile(theBlob, fileName) {
				theBlob.lastModifiedDate = new Date(); // 文件最后的修改日期
				theBlob.name = fileName; // 文件名
				return new File([theBlob], fileName, {
					type: theBlob.type,
					lastModified: Date.now(),
				});
			},
			//清除
			clear() {
				this.$refs.signatureRef.clear()
			},
			//撤销按钮
			undo() {
				this.$refs.signatureRef.undo()
			},
			//签字的按钮
			handleSign(val) {


				this.$refs.popup.open('center')
			},
			//关闭抽屉
			closeDrawer() {
				this.$refs['showLeft'].close()
			},


			//处理详情接口数据回写上面
			handleopen(data) {
				this.valiFormData = data;

				this.valiFormData.approverIds = data.approverIds?.map((item) => {
					return {
						approverId: item,
					};
				});
				this.valiFormData.planUserName = data.examineExecutorName;
				this.valiFormData.pageStatus = this.queryForm.pageStatus
				this.userList = [
					...data.participantVo,
					...data.approverVo,
				]; //参与人和审批人结合到一起

				let arr = data.examineParticipantIds.split(",");
				this.valiFormData.examineParticipantIds = arr?.map((item) => {
					return Number(item);
				});

				this.tableData = data.hiddentroubleInspectionTables;
			},
			/** 被检查部门部门下拉树结构 */
			async getDeptTree() {
				const response = await deptTreeSelect();
				this.treeData = response.data;
			},


			//手工选择返回
			manualCheckBack(val) {
				// console.log("返回的", val)
				this.tableData = val
			},
			init() {

				this.valiFormData.deptId = [this.deptId]
			},
			submit(ref) {
				this.$refs[ref]
					.validate()
					.then(async (res) => {
						this.valiFormData.deptId = this.valiFormData.deptId.toString()

						let {
							id,
							approvalStatus,
							fileInfoList,
							approvalRemark,
							subContractorId
						} = this.valiFormData

						let query = {
							id,
							approveStatus: approvalStatus,
							approveRemark: approvalRemark,
							fileInfoList,
							subContractorId,
						};

						let response = await submitAllShoot(query);
						uni.showToast({
							title: `提交成功`,
						});
						uni.navigateTo({
							url: "/pages/trouble/index"
						})


					})
					.catch((err) => {
						console.log("err", err);
					});
			},
		},
		mounted() {
			this.getDeptTree()
			this.init()
		},
		computed: {
			...mapGetters(["allUsers", "deptId"]),
		}
	};
</script>

<style lang="scss" scoped>
	.workApply-container {
		padding: 20rpx;
		background-color: #fff;
		overflow-y: auto;

		.title {
			margin: 20rpx 0;
			height: 60rpx;
			font-family: PingFangSC, PingFang SC;
			font-weight: 600;
			font-size: 32rpx;
			color: #515a6e;
			text-align: left;
			font-style: normal;
		}

		// 动火负责人签字
		.charge-people {
			position: relative;
			padding: 20rpx;
			background: #ffffff;
			border-radius: 20rpx;
			border: 2rpx solid #dcdee2;

			.check-box {
				margin-right: 20rpx;
			}

			.sign {
				margin-top: 20rpx;
				height: 240rpx;
				background: #ffffff;
				border-radius: 10rpx;
				border: 2rpx dashed #dcdee2;
				font-family: PingFangSC, PingFang SC;
				font-weight: 500;
				font-size: 32rpx;
				color: #c5c8ce;
				line-height: 200rpx;
				text-align: center;
				font-style: normal;
			}

			.time {
				position: absolute;
				bottom: 20rpx;
				right: 5%;
				font-family: PingFangSC, PingFang SC;
				font-weight: 400;
				color: #808695;
				font-style: normal;
			}
		}

		::v-deep {
			.uni-forms-item--border {
				border-top: 0 solid #000;
				border-bottom: 2rpx solid #e8eaec;
			}

			.uni-forms-item__label {
				width: 40% !important;
			}

			.submit-btn {
				margin-top: 30rpx;
				background: #137ee9;
				border-radius: 10rpx;
			}
		}
	}
</style>